﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO;
using System.Text.RegularExpressions;

namespace WinFormsApp1
{
    public partial class BeiXie : Form
    {
        private string[] lstLines;
        private int idx;
        string eng;

        public BeiXie()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            string strFile;
            try
            {
                strFile = File.ReadAllText(openFileDialog1.FileName);
                if (strFile == "") return;
            }
            catch
            {
                MessageBox.Show("无法读取文件！");
                return;
            }


            Regex rgx = new(@"(?:\[.+\])|(?:\n+(?=\n))|(?:\t+(?=\t))");
            strFile = rgx.Replace(strFile, "").Trim();
            lstLines = strFile.Split("\n");
            idx = 0;
            string[] words = lstLines[idx].Split("\t");


            eng = words[0].Trim();
            chineseOutput.Text = words[1];
            if (words.Length == 3) { phoneticOutput.Text = words[2]; } else { phoneticOutput.Clear(); };
            idx++;
        }

        private void buttonNewFile_Click(object sender, EventArgs e)
        {
            englishInput.Clear();
            openFileDialog1.ShowDialog();
        }


        // 与KeyUp和KeyDown不同，KeyPress只有在目标具有焦点时才会触发，且是事后触发，不妨碍其它组件对按键事件的响应。
        // TM卡了好几天，老子还以为键盘坏了！！！
        private void englishInput_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                if (englishInput.Text == "")
                {
                    if (idx == lstLines.Length) idx = 0;

                    string[] words = lstLines[idx].Split("\t");
                    eng = words[0].Trim();
                    chineseOutput.Text = words[1];
                    if (words.Length == 3) { phoneticOutput.Text = words[2]; } else { phoneticOutput.Clear(); };
                    idx++;
                }
                else if(englishInput.Text == eng)
                {
                    englishInput.Clear();
                }
                else
                {
                    MessageBox.Show(this, "是不是不小心打错了？再仔细检查一下吧。", "错了哟", MessageBoxButtons.OK, MessageBoxIcon.Error );
                    englishInput.SelectAll();
                }
            }
        }
    }
}